(function() {
  var express, fs, iced, mkdirp, mmm, moment, multer, path, pgcopy, pgsql, router, uploader, uuid, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  express = require('express');

  fs = require('fs');

  path = require('path');

  uuid = require('uuid');

  pgsql = require('pg');

  moment = require('moment');

  mkdirp = require('mkdirp');

  pgcopy = require('pg-copy-streams');

  multer = require('multer');

  mmm = require('mmmagic');

  router = express.Router();

  module.exports = router;

  router.all('/', function(req, res, next) {
    var client, done, err, result, where_clause, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
        });
        pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              client = arguments[1];
              return done = arguments[2];
            };
          })(),
          lineno: 19
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          done(client);
          return next(err);
        }
        where_clause = "( bin_num like $1 or card_name like $1 or issuer_code like $1 or issuer_name like $1 )";
        if (req.body.card_type && req.body.card_type.length > 0) {
          where_clause += " and card_type = '" + req.body.card_type + "'";
          res.locals.card_type = req.body.card_type;
        }
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
          });
          client.query("select count(*) as count from pay_cardbin where " + where_clause, ['%' + res.locals.keyword + '%'], __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return result = arguments[1];
              };
            })(),
            lineno: 33
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (err) {
            done(client);
            return next(err);
          }
          res.locals.total = result.rows[0].count;
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
            });
            client.query("select * from pay_cardbin where " + where_clause + " order by serial offset $2::int limit $3::int", ['%' + res.locals.keyword + '%', res.locals.offset, res.locals.page_rows], __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  err = arguments[0];
                  return result = arguments[1];
                };
              })(),
              lineno: 44
            }));
            __iced_deferrals._fulfill();
          })(function() {
            if (err) {
              done(client);
              return next(err);
            }
            done();
            return res.render('cardbin/index', {
              records: result.rows
            });
          });
        });
      };
    })(this));
  });

  router.get('/export', function(req, res, next) {
    res.locals.breadcrumbs.push({
      'title': '导出数据'
    });
    return res.render('cardbin/export');
  });

  router.post('/export', function(req, res, next) {
    var client, delimiter, dirname, dnfile, done, down_stream, err, k, stream, today, ___iced_passed_deferral, __iced_deferrals, __iced_k, _i, _len, _ref;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    _ref = ['delim', 'encoding'];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      k = _ref[_i];
      if (!req.body[k]) {
        return next(new Error("请求缺少参数[" + k + "]"));
      }
    }
    if (req.body.delim === 'comma') {
      delimiter = ',';
    } else if (req.body.delim === 'pipe') {
      delimiter = '|';
    } else if (req.body.delim === 'semicolon') {
      delimiter = ';';
    } else {
      return next(new Error('无效的分隔符参数'));
    }
    dirname = settings.dnload_path + "/cardbin";
    mkdirp.sync(dirname);
    today = moment().format('YYYY-MM-DD');
    dnfile = "" + dirname + "/cardbin-" + today + ".txt";
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
        });
        pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              client = arguments[1];
              return done = arguments[2];
            };
          })(),
          lineno: 74
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          done(client);
          return next(err);
        }
        stream = client.query(pgcopy.to("copy pay_cardbin to STDOUT with encoding '" + req.body.encoding + "' delimiter '" + delimiter + "' NULL ''", {
          highWaterMark: 10
        }));
        down_stream = fs.createWriteStream(dnfile, {
          highWaterMark: 10
        });
        stream.on('end', function() {
          var err, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
          __iced_k = __iced_k_noop;
          ___iced_passed_deferral1 = iced.findDeferral(arguments);
          down_stream.close();
          (function(_this) {
            return (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral1,
                filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
              });
              res.download(dnfile, path.basename(dnfile), __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    return err = arguments[0];
                  };
                })(),
                lineno: 84
              }));
              __iced_deferrals._fulfill();
            });
          })(this)((function(_this) {
            return function() {
              fs.unlink(dnfile, function(err) {
                if (err) {
                  return console.error(err);
                }
              });
              res.end();
              return client.end();
            };
          })(this));
        });
        stream.on('error', function(err) {
          return console.error(err.message);
        });
        return stream.pipe(down_stream);
      };
    })(this));
  });

  router.get('/import', function(req, res, next) {
    res.locals.breadcrumbs.push({
      'title': '导入数据'
    });
    return res.render('cardbin/import');
  });

  uploader = multer({
    dest: settings.upload_path
  });

  router.post('/import', uploader.single('attach_file'), function(req, res, next) {
    var client, delimiter, dest_file, dest_path, done, err, file_stream, k, magic, result, stream, today, ___iced_passed_deferral, __iced_deferrals, __iced_k, _i, _len, _ref;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    _ref = ['delim', 'encoding'];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      k = _ref[_i];
      if (!req.body[k]) {
        return next(new Error("请求缺少参数[" + k + "]"));
      }
    }
    if (!req.file) {
      return next(new Error("请求缺少上传数据文件."));
    }
    magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
        });
        magic.detectFile(req.file.path, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              return result = arguments[1];
            };
          })(),
          lineno: 107
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          fs.unlink(req.file.path, function(err) {
            if (err) {
              return console.error(err);
            }
          });
          return next(new Error('不能检测文件类型，导入失败'));
        }
        if (result !== 'text/plain') {
          fs.unlink(req.file.path, function(err) {
            if (err) {
              return console.error(err);
            }
          });
          return next(new Error('上传的文件格式非文本文件，请检查'));
        }
        if (req.body.delim === 'comma') {
          delimiter = ',';
        } else if (req.body.delim === 'pipe') {
          delimiter = '|';
        } else if (req.body.delim === 'semicolon') {
          delimiter = ';';
        } else {
          return next(new Error('无效的分隔符参数'));
        }
        dest_path = "" + settings.upload_path + "/cardbin";
        mkdirp.sync(dest_path);
        today = moment().format('YYYY-MM-DD');
        dest_file = "" + dest_path + "/cardbin-" + today + ".txt";
        fs.rename(req.file.path, dest_file);
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
          });
          pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                client = arguments[1];
                return done = arguments[2];
              };
            })(),
            lineno: 131
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (err) {
            done(client);
            return next(err);
          }
          (function(__iced_k) {
            __iced_deferrals = new iced.Deferrals(__iced_k, {
              parent: ___iced_passed_deferral,
              filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
            });
            client.query("begin", __iced_deferrals.defer({
              assign_fn: (function() {
                return function() {
                  err = arguments[0];
                  return result = arguments[1];
                };
              })(),
              lineno: 134
            }));
            __iced_deferrals._fulfill();
          })(function() {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
              });
              client.query("delete from pay_cardbin", __iced_deferrals.defer({
                assign_fn: (function() {
                  return function() {
                    err = arguments[0];
                    return result = arguments[1];
                  };
                })(),
                lineno: 135
              }));
              __iced_deferrals._fulfill();
            })(function() {
              stream = client.query(pgcopy.from("copy pay_cardbin from STDIN with encoding '" + req.body.encoding + "' delimiter '" + delimiter + "' NULL ''", {
                highWaterMark: 10
              }));
              stream.on('error', function(err) {
                var result, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
                __iced_k = __iced_k_noop;
                ___iced_passed_deferral1 = iced.findDeferral(arguments);
                (function(_this) {
                  return (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral1,
                      filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
                    });
                    client.query("rollback", __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          return result = arguments[1];
                        };
                      })(),
                      lineno: 142
                    }));
                    __iced_deferrals._fulfill();
                  });
                })(this)((function(_this) {
                  return function() {
                    fs.unlink(dest_file, function(err) {
                      if (err) {
                        return console.error(err);
                      }
                    });
                    done(client);
                    return next(err);
                  };
                })(this));
              });
              file_stream = fs.createReadStream(dest_file, {
                highWaterMark: 10
              });
              file_stream.on('end', function() {
                var err, result, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
                __iced_k = __iced_k_noop;
                ___iced_passed_deferral1 = iced.findDeferral(arguments);
                (function(_this) {
                  return (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral1,
                      filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
                    });
                    client.query("commit", __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          return result = arguments[1];
                        };
                      })(),
                      lineno: 149
                    }));
                    __iced_deferrals._fulfill();
                  });
                })(this)((function(_this) {
                  return function() {
                    done();
                    return res.redirect('/cardbin');
                  };
                })(this));
              });
              file_stream.on('error', function(err) {
                var result, ___iced_passed_deferral1, __iced_deferrals, __iced_k;
                __iced_k = __iced_k_noop;
                ___iced_passed_deferral1 = iced.findDeferral(arguments);
                (function(_this) {
                  return (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral1,
                      filename: "/Users/wuxiaohu/lucky-byte/luckpay-web/coffee/routes/cardbin.coffee"
                    });
                    client.query("rollback", __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          return result = arguments[1];
                        };
                      })(),
                      lineno: 153
                    }));
                    __iced_deferrals._fulfill();
                  });
                })(this)((function(_this) {
                  return function() {
                    done();
                    return next(err);
                  };
                })(this));
              });
              return file_stream.pipe(stream);
            });
          });
        });
      };
    })(this));
  });

}).call(this);
